/*
 *  使用空白yuv数据编码h264测试
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include "ffmpeg_codec.h"

#define OUT_FILE "./640x480_30fps.h264"
#define VIDEO_WIDTH 640
#define VIDEO_HEIGHT 480
#define VIDEO_FPS 30

int main(int argc, char **argv)
{
    int ret;
    int fd = 0;
    void *handle = NULL;
    int frameCount = 0;
    FFCodec_Map yuvMap[3];
    uint8_t *frameBuff = NULL;
    uint32_t frameBuffSize = 0;

    printf("\r\n--- %s start ---\r\n", argv[0]);

    //保存h264文件
    fd = open(OUT_FILE, O_RDWR | O_CREAT | O_TRUNC, 0666);
    if (fd < 1)
    {
        printf("create %s failed \r\n", OUT_FILE);
        return -1;
    }

    //编码器初始化
    handle = ffcodec_init(
        CODEC_TYPE_ENCODE,
        CODEC_FORMAT_H264,
        CODEC_FORMAT_YUV420P,
        VIDEO_WIDTH,
        VIDEO_HEIGHT,
        VIDEO_FPS,
        20,
        0);
    if (!handle)
    {
        printf("ffcodec_init: failed \r\n");
        close(fd);
        return -1;
    }

    //空白yuv数据准备
    yuvMap[0].map = (uint8_t*)calloc(VIDEO_WIDTH * VIDEO_HEIGHT, 1);
    memset(yuvMap[0].map, 0x55, VIDEO_WIDTH * VIDEO_HEIGHT);
    yuvMap[0].format = CODEC_FORMAT_YUV420P;
    yuvMap[0].width = VIDEO_WIDTH;
    yuvMap[0].height = VIDEO_HEIGHT;
    yuvMap[0].pb = 1;

    yuvMap[1].map = (uint8_t*)calloc(VIDEO_WIDTH * VIDEO_HEIGHT / 2, 1); //420P格式下UV帧宽只有一半
    memset(yuvMap[1].map, 0x66, VIDEO_WIDTH * VIDEO_HEIGHT / 2);
    yuvMap[1].format = CODEC_FORMAT_YUV420P;
    yuvMap[1].width = VIDEO_WIDTH / 2;
    yuvMap[1].height = VIDEO_HEIGHT;
    yuvMap[1].pb = 1;

    yuvMap[2].map = (uint8_t*)calloc(VIDEO_WIDTH * VIDEO_HEIGHT / 2, 1); //420P格式下UV帧宽只有一半
    memset(yuvMap[2].map, 0x77, VIDEO_WIDTH * VIDEO_HEIGHT / 2);
    yuvMap[2].format = CODEC_FORMAT_YUV420P;
    yuvMap[2].width = VIDEO_WIDTH / 2;
    yuvMap[2].height = VIDEO_HEIGHT;
    yuvMap[2].pb = 1;

    //编码100帧
    do {
        ret = ffcodec_encode(handle, yuvMap, &frameBuff, &frameBuffSize);
        if (ret == 0 && frameBuffSize > 0) {
            printf("ffcodec_encode: frame len/%d - %02X %02X %02X %02X %02X - index %d\r\n",
                frameBuffSize, frameBuff[0], frameBuff[1], frameBuff[2], frameBuff[3], frameBuff[4], frameCount);
            write(fd, frameBuff, frameBuffSize);
            frameCount += 1;
        }
    } while (frameCount < 100);

    //释放内存
    ffcodec_deinit(handle);
    free(yuvMap[0].map);
    free(yuvMap[1].map);
    free(yuvMap[2].map);
    close(fd);

    printf("\r\n--- %s end ---\r\n", argv[0]);
    return 0;
}
